<template>
  <div id="app" class="app-container">
    <div class="header">
      <img src="../assets/叉.png" alt="返回" style=" width: 50px; height: auto; left: 1980px; top: 4px; position: absolute;" @click="goback()" />
      <!-- <el-button type="danger" @click="goback()"
        style="float: right; margin-top: 50px; margin-right: 100px;">退出</el-button> -->
    </div>
    <div class="header-box" style="position: relative; /* 其他样式 */">
      <p style="margin: 28px;">双体软件精英产业学院第484期“我与软件有个约会”</p>
    </div>
    <div class="content">
      <div class="image-container">
        <img :src="imgUrl" alt="头像" class="image-rank-head">
     </div>
      <!-- <div class="score-image">
        <div class="block" v-for="fit in fits" :key="fit.id">
          <span class="demonstration">{{ plaAvatar }}</span>
          <el-image src="../assets/图片2.png" fit="cover"></el-image>
        </div>
      </div> -->
      <div id="main" class="chart-container" style="position: relative; background-color: #f8f2ee !important;">
        这是一个背景透明度为 0.5 的 div 元素
      </div>
      <div class="right-box" style="position: relative; /* 其他样式 */">
        <div class="D-header" style="position: relative;bottom: 20px;">
          <div style="color: #000000; font-weight: bold;font-size: 70px;">得 分</div>
        </div>
        <div class="score-value">
          <span style="color: #000000;font-weight: bold;font-size: 80px;" startscore>{{ avgScore }}</span>
        </div>
        <!-- <div class="score-button" style="position: relative; top: calc(100%  ); right: 20px; width: fit-content;">
          <el-button type="warning" style="height: 100px; margin: 0;width: 400px;" plain
            @click="startscore()">根据评分规则2进行评分</el-button>
        </div> -->
      </div>
    </div>
    <div class="score-xs" style="text-align: left;">
      <div style="font-size: 50px; color: #000000; font-weight: bold; position: absolute; left: 150px; bottom: 270px;">
        <!-- 添加position: absolute; -->
        <span>选手序号：{{ matSequence }}</span>
      </div>
      <div style="font-size: 50px; color: #000000; font-weight: bold; position: absolute; left: 150px;bottom: 190px;">
        <span>当前选手：{{ matName }}</span>
      </div>
    </div>
      <audio controls src="../assets/media/1.mp3" autoplay></audio>
      <img src="../assets/评分大屏背景.png" alt="背景图" style="width: 1920px; height: 1050px; margin: -940px 0 0 10px;">
  </div>
</template> 
<script>
import * as echarts from 'echarts';
import request from '@/utils/request';

export default {
  name: 'XsScoreView',
  components: {},
  data() {
    return {
      chart: null,
      data: [],
      colors: [
        '#ffc75b', '#e4efbe', '#f5d0b7', '#b4d6f8', '#f3b364',
        '#d1dbac', '#ed955f', '#b7cce4', '#efded1', '#ffc75b',
        '#e4efbe', '#b4d6f8', '#ed955f', '#b7cce4', '#f3b364'
      ], // 定义 15 种颜色数组，不包含白色
      ws: null,
      judeNames: [],
      ydb: 2,
      avgScore: 0.0,
      matSequence: '',
      matName: '',
      scores: [],
      hasSameScore: false,
      plaAvatars: [],
      imgUrl: ''
    };
  },
  mounted() {
    this.initChart();
    this.initWebSocket();
    this.image();
  },
  beforeDestroy() {
    this.closeWebSocket();
  },
  created() {
    this.matSequence = sessionStorage.getItem('match_current_matSequence') || '无材料名称';
    this.matName = sessionStorage.getItem('match_current_matName') || '无材料名称';
    // this.plaAvatar = sessionStorage.getItem('player_current_plaAvatar') || '无材料名称';
    this.scores = [this.avgScore];
    // this.checkForSameScores();
  },
  methods: {
    //图片上传
    async fetchPlayerAvatars() {
      try {
        request.post('/players/PlaPhoto'); // 替换为实际的API端点
        if (response.data && Array.isArray(response.data)) {
          this.plaAvatars = response.data.map(avatar => avatar.imageUrl); // 假设后端返回的数据中包含imageUrl属性
        } else {
          console.error('后端返回的数据格式不正确');
        }
      } catch (error) {
        console.error('获取玩家头像时出错:', error);
      }
    },
    // 检查是否有相同的分数
    // checkForSameScores() {
    //   const scoreSet = new Set(); // 使用Set来记录已遇到的分数
    //   for (const score of this.avgScores) {
    //     if (scoreSet.has(avgScore)) {
    //       this.hasSameScore = true; // 发现重复分数，标记为true
    //       return; // 立即返回，无需继续检查
    //     }
    //     scoreSet.add(avgScore); // 将分数添加到Set中
    //   }
    //   this.hasSameScore = false; // 如果没有发现重复分数，标记为false
    // },

    // 异步提交分数
    async submitScore() {
      try {
        // 显示提示信息给用户
        await MessageBox.alert({
          message: '将按照不去掉最高分和最低分的方式重新计算分数',
          title: '提示',
          confirmButtonText: '确定',
          closeOnClickModal: false,
          showClose: false,
          type: 'success',
          duration: 2000 // 显示2秒后自动关闭
        });

        // 发送POST请求以保存分数
        const response = await request.post("/match/rest", {
          id: this.id,
          matScore: this.rest
        });

        // 打印平均分数到控制台
        console.log('平均分数:', this.rest);

        // 导航回比赛页面
        this.$router.push("/match");

        // 处理后端响应的数据
        if (response.data && response.data.score) {
          this.score = response.data.score;
          MessageBox.success('评分已成功提交，当前分数已更新！', '成功');
        } else {
          // 如果没有返回有效的分数数据，则抛出错误
          throw new Error('后端未返回有效的分数数据');
        }
      } catch (error) {
        // 捕获并处理在评分提交过程中发生的错误
        console.error('评分提交过程中发生错误：', error);
        Message.error('评分提交失败，请稍后重试。');
      }
    },
    startscore() {
      // console.log("切换算法")
      // 运行评分规则二并获取分数
      let score = this.submitScore();
    },
    // 返回上一页并保存分数
    goback() {
      const id = sessionStorage.getItem('match_current_id');

      // 打印获取的 id
      console.log('Retrieved user ID:', id);

      request.post("/match/savescore", { id: id, matScore: this.avgScore }).then(res => {
        console.log('Average Score:', this.avgScore);
        // this.$router.push({name:'match'});
        this.$router.back();
        
      }).catch(err => {
        this.$message.error("保存失败");
        console.error(err);
      });
    },
    image(){
      request.post("/player/info",{ id: sessionStorage.getItem('match_current_playId')}).then(res =>{
        const tmp = res.data;
        this.imgUrl=tmp[0].plaPhoto;
        console.log(this.imgUrl);
      })
    },
    // 初始化图表
    initChart() {
      // 初始化数据
      // for (let i = 0; i < 8; ++i) { // 修改为 8 条
      //   this.data.push(Math.round(Math.random() * 200));
      // }

      // 基于准备好的dom，初始化echarts实例
      this.chart = echarts.init(document.getElementById('main'));

      // 设置初始选项
      this.chart.setOption({
        backgroundColor: 'rgba(255, 255, 255, 0.8)', // 背景颜色
        xAxis: {
          max: 100.0,
          axisLine: { lineStyle: { color: '#ccc' } },
          axisLabel: {
            color: '#333',
            fontSize: 30 // 增大 x 轴标签字体大小
          },
          min: 80.0
        },
        yAxis: {
          type: 'category',
          data: this.judeNames, // 修改为 8 条
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 0, // 只显示最大的4个条形图
          axisLine: { lineStyle: { color: '#ccc' } },
          axisLabel: {
            color: '#333',
            fontSize: 30, // 增大 y 轴标签字体大小
          }
        },
        series: [
          {
            realtimeSort: true,
            name: 'X',
            type: 'bar',
            data: this.data,
            fontSize: 30, // 增大数据标签字体大小
            label: {
              show: true,
              position: 'right',
              valueAnimation: true,
              color: '#333',
              fontSize: 30 // 增大数据标签字体大小

            },
            itemStyle: {
              color: (params) => {
                return this.colors[params.dataIndex % this.colors.length]; // 根据索引选择颜色
              }
            }
          }
        ],
        legend: {
          show: true,
          textStyle: { color: '#333' }
        },
        animationDuration: 0,
        animationDurationUpdate: 3000,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear'
      });
    },
    updateChart(data) {
      // 更新数据
      this.data.push(data.judeScore);
      this.judeNames.push("评委" + data.judeId);
      this.avgScore = data.avgScore;

      // 更新图表
      this.chart.setOption({
        yAxis: {
          data: this.judeNames, // 修改为 8 条
          max: this.data.length
        },
        series: [
          {
            type: 'bar',
            data: this.data,
            itemStyle: {
              color: (params) => {
                return this.colors[params.dataIndex % this.colors.length]; // 根据索引选择颜色
              }
            }
          }
        ]
      });
    },
    initWebSocket() {
      // WebSocket URL
      //const wsUrl = 'ws://8.137.118.148:8905/chat/' + sessionStorage.getItem('match_current_playId');
      const wsUrl = `${this.$config.apiUrl.replace(/\/$/, '')}/chat/${sessionStorage.getItem('match_current_playId')}`;
  
      

      // 创建 WebSocket 连接
      this.ws = new WebSocket(wsUrl);

      // 连接打开时触发
      this.ws.onopen = () => {
        console.log('WebSocket connection opened');
      };

      // 接收到消息时触发
      this.ws.onmessage = (event) => {
        const newData = JSON.parse(event.data);
        this.updateChart(newData);
      };

      // 连接关闭时触发
      this.ws.onclose = () => {
        console.log('WebSocket connection closed');
      };

      // 发生错误时触发
      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
    },
    closeWebSocket() {
      if (this.ws) {
        this.ws.close();
      }
    }
  }
};
</script>

<style scoped>
 @font-face {
  /* font-family: 'DingTalkJinBuTi';
  src: url('../assets/fonts/DingTalkJinBuTi.ttf') format('truetype'); */
  font-family: '方正汉真广标简体';
  src: url('../assets/fonts/方正汉真广标简体.TTF') format('truetype');
  font-weight: normal;
  font-style: normal;
}

.app-container {
  width: 100%;
  height: 100vh;
  background-color: #f8f2ee;
  font-family: '方正汉真广标简体', sans-serif;
  /* background-image: url('../assets/评分大屏背景.png'); */
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding-top: 100px;
}

.header {
  width: 100%;
  position: absolute;
  top: 0;
  z-index: 10;
  float: right;
}

.header-box {
  margin: 10px 0;
  width: 1800px;
  height: 120px;
  justify-content: center; 
  font-size: 60px;
  text-align: center;
  border-radius: 20px;
  align-items: center;
  background-color: #fae6c3;
  float: left;
  z-index: 10;
}

.content {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 0 50px;
}

.chart-container {
  width: 50%;
  height: 750px;
  background-color: transparent;
  /* 背景色 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 100px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-box {
  margin: 250px 65px 0 0;
  width: 18%;
  height: 260px;
  border-radius: 20px;
  background-color: #fae6c3;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.score-header {
  width: 100%;
  height: 100px;
  background: linear-gradient(to bottom right,
      rgba(255, 215, 0, 0.8),
      rgba(218, 165, 32, 0.4),
      rgba(184, 134, 11, 0.2));
  border-radius: 28px 28px 0 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.image-container {
  width: 380px;
  height: 500px;
  margin: 50px 0 0 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.image-container img {
    width: 100%;
    height: 100%;
    border-radius: 20px;
    object-fit: cover;
}

.block{
  width: 100%;
  height: 100%;
}


.score-value {
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
